package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.fsd.admin.dao.E_SystemcodeDao;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.E_Systemcode;
import com.fsd.admin.service.E_SystemcodeService;
import com.fsd.core.util.Config;
import com.fsd.core.util.EhcacheUtil;

@Service("e_systemcodeServiceImpl")
public class E_SystemcodeServiceImpl extends MainServiceImpl<E_Systemcode, String> implements E_SystemcodeService {

	private static final Logger log = Logger.getLogger(E_SystemcodeServiceImpl.class);
    private String depict = "";
	
    @Resource(name = "e_systemcodeDaoImpl")
	public void setBaseDao(E_SystemcodeDao e_systemcodeDao) {
		super.setBaseDao(e_systemcodeDao);
	}
    
	@Resource(name = "e_systemcodeDaoImpl")
	private E_SystemcodeDao objectDao;
	
	private static final Lock lock = new ReentrantLock();
	
	/**
	 * 获取缓存数据集合
	 * @param id
	 * @return
	 */
	private Map<String, E_Systemcode> getObjectList(String companyid) throws Exception{
		lock.lock();
		Map<String, E_Systemcode> objectMap = null;
		String strKey = Config.E_SYSTEMCODEMAP + companyid;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				List<E_Systemcode> allObjectList = objectDao.queryByHql("from E_Systemcode t where t.companyid in ('" + companyid + "','0') order by t.code");
				objectMap = new HashMap<String, E_Systemcode>();
				for (E_Systemcode obj : allObjectList) {
					objectMap.put(obj.getCode(), obj);
				}
				EhcacheUtil.getInstance().put(strKey, objectMap);
			}else{
				objectMap = (Map<String, E_Systemcode>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		return objectMap;
	}
	
	/**
	 * 获取缓存数据
	 * @param id
	 * @return
	 */
	private E_Systemcode getObjectByID(String id, String companyid) throws Exception{
		lock.lock();
		Map<String, E_Systemcode> objectMap = this.getObjectList(companyid);
		if (objectMap != null && objectMap.containsKey(id)){
			return objectMap.get(id);
		}
		return null;
	}
	
	/**
	 * 加载对象集合
	 * @return
	 * @throws Exception
	 */
	public List<E_Systemcode> getObjectListByCompanyID(A_Employee employee) throws Exception{
		Map<String, E_Systemcode> objectMap = this.getObjectList(employee.getCompanyid());
		List<E_Systemcode> objList = new ArrayList<E_Systemcode>();
		for (E_Systemcode obj : objectMap.values()) {
			objList.add(obj);
		}
		return objList;
	}
}
